package com.bit.bit_forum.service.impl;

import com.bit.bit_forum.common.AppResult;
import com.bit.bit_forum.common.ResultCode;
import com.bit.bit_forum.dao.UserMapper;
import com.bit.bit_forum.exception.ApplicationException;
import com.bit.bit_forum.model.User;
import com.bit.bit_forum.service.IUserService;
import com.bit.bit_forum.utils.MD5Util;
import com.bit.bit_forum.utils.StringUtil;
import com.bit.bit_forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 创建普通用户
     * @param user
     */
    @Override
    public void createNormUser(User user) {
        //1.数据非空校验
        if(user==null || StringUtil.isEmpty(user.getUsername())
        || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常,统一为ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.按用户名查询用户信息
        User user1 = userMapper.selectByUserName(user.getUsername());
        //判断用户是否已经存在
        if(user1!=null){
            //打印日志,抛出异常
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        //3.新增用户,设置默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteStat((byte)0);
//        这个获取到的时间比当前时间要晚8小时
//        Date date = new Date();
        // 直接在Instant上增加8小时，再转回Date
        Date date = Date.from(
                Instant.now().plus(8, ChronoUnit.HOURS)
        );
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //4.写入数据库
        //调用弹性参数方法 ,返回生成条数
        int n = userMapper.insertSelective(user);
        if(n!=1){
            //打印日志,抛出异常
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //添加成功,打印日志
        log.info("新增用户: name:"+user.getUsername());
    }

    @Override
    public User selectByUserName(String name) {
        //1.数据非空校验
        if(StringUtil.isEmpty(name)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByUserName(name);
    }

    @Override
    public User login(String name, String password) {
        //参数 1.非空校验
        if(StringUtil.isEmpty(name) || StringUtil.isEmpty(password)){
            //打印日志,参数校验失败
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.按用户名 查询用户信息
        User user = selectByUserName(name);
        if(user==null){
            //打印日志 登录失败
            log.warn(ResultCode.FAILED_LOGIN.toString()+" username: "+name);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //3,对密码进行校验
        String salt= user.getSalt();
        String psw = MD5Util.md5Salt(password,salt);
        if(!psw.equalsIgnoreCase(user.getPassword())){
            //密码错误
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //登录成功
        log.info("登录成功,username: "+name);
        return user;
    }

    @Override
    public User getById(Long id) {
        if(id==null){
            //打印日志,参数校验失败
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString()+" id: "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int n = userMapper.updateByPrimaryKeySelective(updateUser);
        if(n!=1){
            log.warn(ResultCode.FAILED.toString()+" 受影响的行数不是 1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.ERROR_IS_NULL.toString()+" id: "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户发帖数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        //对数据合法性矫正：
        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int n = userMapper.updateByPrimaryKeySelective(updateUser);
        if(n!=1){
            log.warn(ResultCode.FAILED.toString()+" 受影响的行数不是 1.");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void updateUserInfo(User user) {
        //非空校验:
        if(user==null || user.getId()==null || user.getId()<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        //判断要修改的用户是否存在:
        if(existUser==null || existUser.getDeleteStat()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //check: 校验是否要修改:
        boolean check = false;//为false时表示校验失败
        User updateUser = new User();
        updateUser.setId(user.getId());

        //若修改用户名:
        if(!StringUtil.isEmpty(user.getUsername())
                && !user.getUsername().equals(existUser.getUsername())){
            User user1 = userMapper.selectByUserName(user.getUsername());
            //要修改的用户名已经存在:出现重名:
            if(user1!=null){
//            System.out.println("user1: "+user1);
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            check = true;
        }
        //修改昵称
        if(!StringUtil.isEmpty(user.getNickname()) &&  !user.getNickname().equals(existUser.getNickname())){
            updateUser.setNickname(user.getNickname());
            check = true;
        }
        //修改性别:
        if(user.getGender()!=null && user.getGender() != existUser.getGender()){
            updateUser.setGender(user.getGender());
            if(updateUser.getGender()>2 || updateUser.getGender()<0){
                updateUser.setGender((byte)2);
            }
                check = true;
        }
        //修改邮箱
        if(!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            check = true;

        }
        //修改电话号码:
        if(!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            check = true;
        }
        //修改个人简介
        if(!StringUtil.isEmpty(user.getRemark())
                &&  !user.getRemark().equals(existUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            check = true;
        }
        if(check == false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int n = userMapper.updateByPrimaryKeySelective(user);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void updateUserPwd(Long id, String oldPasssword, String newPassword) {
        //1.参数校验:
        if(id==null || id<=0 || StringUtil.isEmpty(oldPasssword) || StringUtil.isEmpty(newPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        String salt = user.getSalt();
        String password = MD5Util.md5Salt(oldPasssword, salt);
        //判断输入的密码是否正确,注意要忽略大小写,因为加盐后不确定两次的大小写
        if(!password.equalsIgnoreCase(user.getPassword())){
            //密码有误:
            log.warn(ResultCode.FAILED_PASSWORD_ERROR.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PASSWORD_ERROR));
        }
        String newSalt = UUIDUtil.UUID_32();
        newPassword = MD5Util.md5Salt(newPassword, newSalt);
        //创建要修改的对象:
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(newPassword);
        updateUser.setSalt(newSalt);
        //修改到数据库:
        int n = userMapper.updateByPrimaryKeySelective(updateUser);
        if(n!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
}
